console.log("wechat data");

let setTimeNum = 0;

// 定时任务
async function checkPages() {
  /**
   * @since 2025-03-04 读取page
   */
  let requestPage = await GetRequestPage();
  let requestPageStart = requestPage.start;
  let requestPageNow = requestPage.now;
  let requestPageEnd = requestPage.end;

  /**
   * @since 2025-03-06 判断是否需要执行采集任务
   */
  if(requestPageStart == 0 || (requestPageNow > requestPageEnd)){
    console.log("采集任务等待中" + '.'.repeat(setTimeNum % 6 + 1));
    setTimeNum++;
    setTimeout(checkPages, 1000);
  } else {
    /**
     * @since 2025-03-04 执行采集任务
     */
    let url = "https://mp.weixin.qq.com/cgi-bin/appmsgpublish";
    let param = await GetStorage("wx_request_param");

    /**
     * @since 2025-03-04 修改页码
     * @since 2025-03-06 这里发起请求，会被background.js监听到，param.begin会变化
     */
    param.begin = requestPageNow*5-5;
    console.log("准备提交的参数", param);

    /**
     * @since 2025-03-04 拼接参数，Get请求数据
     */
    $.get(url, param)
      .done(function(response) {
        /**
         * @since 2025-03-05 保存采集页码
         */
        requestPage.now++;
        SetStorage("request_page", requestPage);

        /**
         * @since 2025-03-05 增加微信号
         * @since 2025-03-06 添加公众号名称
         */
        response.fakeid = param.fakeid;
        response.nickname = requestPage.nickname;
        console.log('请求成功', response);

        /**
         * @since 2025-03-04 通知background
         */
        chrome.runtime.sendMessage({action: "save-weixin-data", data: response});

        /**
         * @since 2025-03-05 继续执行任务
         */
        setTimeout(checkPages, 15*1000);
      })
      .fail(function(jqXHR, textStatus, errorThrown) {
        console.error('请求失败:', textStatus, errorThrown);
      });
  }
}

$(document).ready(function(){
  // 启动定时任务
  checkPages();
});